/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:

    struct cmp
    {
        bool operator()(ListNode* l1, ListNode* l2)
        {
            return l1->val > l2->val;
        }
    };

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        //if(lists.empty() || lists[0] == nullptr) return nullptr;
        ListNode* head = new ListNode(0);
        priority_queue<ListNode*, vector<ListNode*>, cmp>  hp;

        for (auto node : lists)
        {
            if (node)
                hp.push(node);
        }

        ListNode* prev = head;
        while (!hp.empty())
        {
            ListNode* t = hp.top();
            hp.pop();
            if (t->next)
                hp.push(t->next);
            prev->next = t;
            prev = t;
        }
        return head->next;
    }
};